package com.example.emos.wx.user.filter;

import com.example.emos.wx.user.wrapper.XssHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 抵御XSS过滤器
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/7/26
 */
//过滤器拦截的路径是所有的路径
@WebFilter(urlPatterns = "/*")
public class XssFilter implements Filter {
    /**
     * 继承父类的初始化方法
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 在容器接收到请求时进行过滤的处理
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //使用装饰器封装的Wrapper
        XssHttpServletRequestWrapper wrapper = new XssHttpServletRequestWrapper(request);
        //往后传的内容不是直接的请求而是被Wrapper装饰后也就是对请求参数进行转义后的请求所以需要传入wrapper
        filterChain.doFilter(wrapper, servletResponse);
    }

    /**
     * 继承父类的销毁方法
     */
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
